% 适应度函数：计算波束形成向量并考虑天线间最小间距约束
function fitness = beamformingFitness(positions, numTransmitAntennas, numReceiveAntennas)
    % 解析发送天线位置
    tx_x = positions(1:numTransmitAntennas);
    tx_y = positions(numTransmitAntennas + 1:numTransmitAntennas * 2);
    tx_pos = [tx_x; tx_y];
    
    % 解析接收天线位置
    rx_x = positions(numTransmitAntennas * 2 + 1:numTransmitAntennas * 2 + numReceiveAntennas);
    rx_y = positions(numTransmitAntennas * 2 + numReceiveAntennas + 1:end);
    rx_pos = [rx_x; rx_y];
    
    fprintf('Evaluating positions...\n');
    fprintf('发送天线位置:\n');
    disp(tx_pos);
    fprintf('接收天线位置:\n');
    disp(rx_pos);
    
    % 假设目标方向矢量 (示例)
    steeringVector = [1; 0];
    
    % 计算波束形成向量
    try
        cvx_begin quiet
            variable w(numTransmitAntennas) complex;
            minimize(norm(w));  % 最小化波束形成向量的范数
            subject to
                abs(w' * (tx_pos' * steeringVector)) >= 1;  % 满足波束指向约束
        cvx_end
    catch
        % 如果 CVX 求解失败，给予较大惩罚
        fitness = 1e6;
        fprintf('CVX 求解失败，给予惩罚。\n');
        return;
    end

    % 计算发送天线间和接收天线间最小间距约束
    minDistance = 0.5; % 设定最小间距阈值
    txPairwiseDistances = pdist(tx_pos');
    rxPairwiseDistances = pdist(rx_pos');
    distancePenalty = (sum(txPairwiseDistances < minDistance) + sum(rxPairwiseDistances < minDistance)) * 1e3;

    % 适应度 = 波束形成向量的范数 + 间距惩罚
    fitness = norm(w) + distancePenalty;
    fprintf('当前适应度值: %.4f\n', fitness);
end